#include "ImageProcessor.h"
#include "errordialogmanager.h"
#include "faultcachemodel.h"
#include "ngtable.h"
#include "pccore.h"
#include "pccoremodel.h"

FaultCacheModel &FaultCacheModel::instance() {
    static FaultCacheModel instance;
    return instance;
}


void FaultCacheModel::displaycurrentCacheNum(int currentCacheNum)
{
    if(currentCacheNum_ != currentCacheNum)
    {
        currentCacheNum_ = currentCacheNum;
        emit currentCacheNumChange();
    }
}
void FaultCacheModel::removeRowByIndex(int index) {
    //qDebug() << "1";
    {
        QMutexLocker locker(&mutex_); // 锁定互斥量以保证线程安全
        //qDebug() << "2";
        // 检查索引是否有效
        if (index < 0 || index >= m_imgCardCache.size()) {
            qWarning() << "Index out of range: " << index;
            return;
        }

        beginRemoveRows(QModelIndex(), index, index); // 开始删除行
        m_imgCardCache.removeAt(index); // 从缓存中删除指定行
        endRemoveRows(); // 结束删除行
    }

    displaycurrentCacheNum(m_imgCardCache.size()); // 更新当前缓存数量
    emit currentCacheNumChange(); // 通知视图当前缓存数量已变化
}


void FaultCacheModel::addDataItem(ImageRecord imgCard) {
    QMutexLocker locker(&mutex_); // 锁定互斥量以保证线程安全

    FaultImageCacheItem item;
    item.id = imgCard.getID();
    qInfo() << " FaultCacheModel addDataItem imgCard.getState()" << imgCard.getState();
    if(imgCard.getState() == ImageRecord::Succeed)
    {
        std::vector<int> ngList = imgCard.getNgCard().getDefects();
        if(!ngList.empty())
        {
            item.detail = NGTable::getInstance().parseNGListToDescription(ngList);
        }else
        {
            return;
        }
    }else{
        item.detail = "故障 未进行完全检测";
    }
    item.time = imgCard.getElapsedTime();
    item.resultImage = imgCard.getResultImage();
    item.ngcard = imgCard.getNgCard();
    item.imageList = imgCard.emphasizeCurentList;
    item.aiImage = imgCard.imageRote;
    item.isTrain = false;
    item.imagePointList = imgCard.emphasizeCurentPointList;
    qInfo() << "Added item id=" << item.id << " detail=" << item.detail;
    beginInsertRows(QModelIndex(), 0, 0); // 在模型的开始处插入新行
    m_imgCardCache.prepend(item); // 将新项目添加到开始处
    endInsertRows();

    if (m_imgCardCache.size() > 30) {
        beginRemoveRows(QModelIndex(), m_imgCardCache.size() - 1, m_imgCardCache.size() - 1);
        m_imgCardCache.removeLast(); // 移除最后一项
        endRemoveRows();
    }
    displaycurrentCacheNum(item.id);
}

QVariant FaultCacheModel::data(const QModelIndex &index, int role) const {
    QMutexLocker locker(&mutex_); // 锁定互斥量以保证线程安全
    if (!index.isValid() || index.row() >= m_imgCardCache.size()) {
        LogError << "Invalid index accessed: " << index.row();
        return QVariant();
    }

    const FaultImageCacheItem &item = m_imgCardCache.at(index.row());
    switch (role) {
    case IdRole:
        return item.id;
    case DetectDetailRole:
        return item.detail;
    case DetectTimeRole:
        return item.time;
    default:
        return QVariant();
    }
}

int FaultCacheModel::rowCount(const QModelIndex &parent) const {
    //LogDebug << "rowCount" << m_cache.size();
    return m_imgCardCache.size();
}

QHash<int, QByteArray> FaultCacheModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[IdRole] = "id";
    roles[DetectDetailRole] = "detail";
    roles[DetectTimeRole] = "time";
    return roles;
}

FaultCacheModel::FaultImageCacheItem FaultCacheModel::getImageEmListBy(int index) {
    // 检查索引是否超出范围
    if (index < 0 || index >= m_imgCardCache.size()) {
        qWarning() << "Index out of range: " << index;
        return FaultImageCacheItem();
    }

    return m_imgCardCache.at(index);
}


void FaultCacheModel::displayEmChart(int id)
{
    QMutexLocker locker(&mutex_); // 锁定互斥量以保证线程安全
    for (FaultImageCacheItem& item : m_imgCardCache) {
        if (item.id == id) {
            LogDebug << "displayEmChart Retrieved ImageRecord with id=" << id;
            cv::Mat img = item.resultImage;
            cv::Mat aiimg = item.aiImage;
            ImageProvider::getInstance().image2qml(img, "pop2");
            ImageProvider::getInstance().image2qml(aiimg, "pop");
            emit characterDetectionimgChanged();
            return;
        }
    }
    LogWarning << "No ImageRecord found with id=" << id;
}

void FaultCacheModel::ClearCacheNum()
{
    QMutexLocker locker(&mutex_);
    okNum_ = 0;
    LogInfo << "Attempting to DetectCacheModel::ClearCacheNum ";
    if (!m_imgCardCache.isEmpty()) {
        beginRemoveRows(QModelIndex(), 0, m_imgCardCache.size() - 1);
        m_imgCardCache.clear();
        endRemoveRows();
    }
    index = 0; // 重置索引
    displaycurrentCacheNum(index);
    emit clearDetectCache();
    emit currentCacheNumChange(); // 通知视图当前缓存数量已变化
}

void FaultCacheModel::displayImageRecordById(int id) {
    QMutexLocker locker(&mutex_); // 锁定互斥量以保证线程安全
    for (FaultImageCacheItem& item : m_imgCardCache) {
        if (item.id == id) {
            ImageProcessor::getInstance().setdisplayHistory(true);
            LogDebug << "Retrieved ImageRecord with id=" << id;
            cv::Mat img = item.resultImage;
            ImageProcessor::getInstance().displayOKNGReson(item.ngcard);
            ImageProvider::getInstance().image2qml(img, "Main");
            return;
        }
    }
    LogWarning << "No ImageRecord found with id=" << id;
}

void FaultCacheModel::eyeaADDTrain(int id)
{
    QMutexLocker locker(&mutex_); // 锁定互斥量以保证线程安全
    for (FaultImageCacheItem& item : m_imgCardCache) {
        if (item.id == id) {
            cv::Mat image_ =item.aiImage.clone();
            (void)QtConcurrent::run([this , image_]() {
                cv::Mat image = image_.clone();
                image = PCcore::getInstance().cropImage(image);
                void *result = PCcore::getInstance().getpcFutre().detect(image);
                PCcoreModel::instance().addItem(result , image);
                PCcoreModel::instance().emitDataCollectionComplete();
            });
            return;
        }
    }
    LogWarning << "No ImageRecord found with id=" << id;
}


void FaultCacheModel::setcurrentCacheSeclectId( int id )
{
    if(id != currentCacheSeclectId_)
    {
        currentCacheSeclectId_ = id;
        displayImageRecordById(currentCacheSeclectId_);
        emit currentCacheSeclectIdChange();
    }
}

FaultCacheModel::FaultCacheModel(QObject *parent) : QAbstractListModel(parent) {
    // Add some dummy data for debugging
    // connect(&ConfigManager::getInstance(), &ConfigManager::valueTableLoad, this, &FaultCacheModel::valueTableLoad);
    // cacheNum_ = ParamValue.getParameter<int>("base","cachequantity") > 0 ?
    //                 ParamValue.getParameter<int>("base","cachequantity")  : 1;

    currentCacheSeclectId_ = -1;
    index = 0;
    displaycurrentCacheNum(index);
}
